package xp2p.global.comm;

import java.io.IOException;
import java.net.UnknownHostException;

import xp2p.global.Client;

import net.jxta.peer.PeerID;


/**
 * The Class ClientProvider.
 */
public class ClientProvider
{
	private PeerID id;
	private Client client;
	
	public ClientProvider(PeerID id)
	{
		this.id = id;
	}
	
	private void checkClient() throws UnknownHostException, IOException
	{
		if (client == null)
		{
			createClient();
			return;
		}
		if (client.wasClosed())
		{
			createClient();
		}
	}

	private void createClient() throws UnknownHostException, IOException
	{
		client = new Client(id);
		client.connect();
		return;
	}
	
	public Client getClient() throws UnknownHostException, IOException
	{
		checkClient();
		return client;
	}
	
	public void close()
	{
		if (client == null)
		{
			return;
		}
		client.close();
		client = null;
	}
	
	public boolean IsOpened()
	{
		return client != null;
	}
}
